package cn.sdack.go.client1.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.http.*;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Controller
public class AuthorizationController {




    @GetMapping(value = "/authorize", params = "grant_type=authorization_code")
    public String authorizationCodeGrant(Model model,
                                         @RegisteredOAuth2AuthorizedClient("client-code")
                                                 OAuth2AuthorizedClient authorizedClient) {

        // 请求资源服务器
        OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
        String token = accessToken.getTokenValue();
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer "+token);
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(null, headers);
        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange("http://localhost:8081/index", HttpMethod.GET, entity,JSONObject.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            System.out.println("请求成功===========");
        } else {
            System.out.println("请求失败===========");
        }
        JSONObject body = responseEntity.getBody();
        if (body != null) {
            JSONArray data = body.getJSONArray("data");
            List<String> lists = data.toJavaList(String.class);
            model.addAttribute("messages", lists);
        }

        return "index";
    }


}
